package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"wechat/models/mysql"

	"wechat/wechatrpc/internal/svc"
	"wechat/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PerfectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPerfectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PerfectLogic {
	return &PerfectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PerfectLogic) Perfect(in *wechatrpc.PerfectRequest) (*wechatrpc.PerfectResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User

	if err := findUser.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, err
	}

	if in.WechatCode == findUser.WechatCode {
		return nil, errors.New("微信号与原微信号一致")
	}

	var findUserByWechatCode mysql.User

	if err := findUserByWechatCode.FindUserByWechatCode(mysql.DB, in.WechatCode); err != nil {
		return nil, err
	}

	if findUserByWechatCode.ID != 0 {
		return nil, errors.New("微信号已被占用,请更改微信号")
	}

	user := &mysql.User{
		Model:      gorm.Model{ID: uint(in.UserId)},
		NickName:   in.NickName,
		WechatCode: in.WechatCode,
		Qq:         in.Qq,
		Email:      in.Email,
		HeadImage:  in.HeadImage,
	}

	if err := user.UserPerfect(mysql.DB); err != nil {
		return nil, err
	}

	return &wechatrpc.PerfectResponse{
		UserId: int64(user.ID),
	}, nil
}
